//
//  HTTripViewController.m
//  HeartTravel
//
//  Created by lanou on 15/10/26.
//  Copyright © 2015年 陈文杰. All rights reserved.
//

#import "HTTripViewController.h"
#import "HTTTrippTableViewCell.h"
#import "PKRequestManager.h"
#import "HTTripMainModel.h"
#import "HTTripListModel.h"
#import "MJRefresh.h"
#import "HTTripDeatillViewController.h"
#import "FMDatabase.h"
#define TripURL @"http://api.daizhe.cn/v2_4/experience?device_type=2&ac=list&cur_version=2.3.5.1&current_date=1445611206&device_code=77FEFD37-68DD-413D-8097-32017A5C6634&device_token=21093eff1a82bf7778421dddfcf93b2e&dz_token=&dz_uid=&order=1&page="

@interface HTTripViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    int page;
    int addPage;
}
@property (nonatomic, strong) HTTripMainModel *tripMainModel;
@property (nonatomic, strong) FMDatabase *dataBase;//数据库
@end

@implementation HTTripViewController

- (NSMutableArray *)array
{
    if (!_array)
    {
        _array = [NSMutableArray array];
    }
    return _array;
}

- (void)requestData:(int)pagee
{
    NSString *pageStr = [NSString stringWithFormat:@"%d",pagee];
    NSString *urlstr = [self page:pageStr];
    
    [PKRequestManager requestWithType:GET urlString:urlstr parDic:nil finish:^(NSData *data) {
        
       // [self.array removeAllObjects];
        //下拉的时候清空数组
        if (pagee == page)
        {
            [self.array removeAllObjects];
        }
        
        NSMutableDictionary *dic2 = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves) error:nil];
        NSDictionary *listDic = dic2[@"responseData"][@"list"];
        for (NSDictionary *key in listDic)
        {
            _tripMainModel = [[HTTripMainModel alloc]init];
            
            [_tripMainModel setValuesForKeysWithDictionary:key];
            
            [self.array addObject:_tripMainModel];
            
            [_dataBase executeUpdate:@"insert into Trip (relate_img, experience_title, apply_cnt) values (?,?,?)",_tripMainModel.relate_img,_tripMainModel.experience_title, _tripMainModel.apply_cnt];
        }
        
        [self.tableView reloadData];
        
    } error:^(NSError *error) {
        NSLog(@"践行页面加载失败%@",error);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    page = 1;
    addPage = 2;
    [self requestData:page];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-150) style:(UITableViewStylePlain)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.rowHeight = 180;
    
    //把子视图在父视图上多出的部分剪裁掉
   // self.tableView.clipsToBounds = YES;
    
    [self.tableView registerClass:[HTTTrippTableViewCell class] forCellReuseIdentifier:@"reuser"];
    [self.view addSubview:self.tableView];
    
    //下拉刷新
    __weak HTTripViewController *HTTripVC = self;
    _tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [HTTripVC requestData:page];
        [_tableView.header endRefreshing];
    }];
    
    //上提加载更多
    _tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [HTTripVC requestData:addPage];
        [_tableView.footer endRefreshing];
        addPage ++;
    }];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appear) name:@"detailVC" object:nil];
    
#pragma mark --- 数据持久化
    
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"HeartTravel.db"];
    _dataBase = [FMDatabase databaseWithPath:filePath];
  //  NSLog(@"数据库路径filePath = %@", filePath);

    if ([_dataBase open]) {
        [_dataBase executeUpdate:@"create table Trip (relate_img text, experience_title text, apply_cnt text)"];
    }else{
        NSLog(@"数据库没有打开");
    }
    
#pragma mark -- 从数据库里面取数据
    
    FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"select * from Trip"];
    while ([resultSet next]) {
        NSString *relate_img = [resultSet stringForColumn:@"relate_img"];
        
        NSString *experience_title = [resultSet stringForColumn:@"experience_title"];
        
        NSString *apply_cnt = [resultSet stringForColumn:@"apply_cnt"];
        
        
        HTTripMainModel *model = [[HTTripMainModel alloc]init];
        
        model.relate_img = relate_img;
        model.experience_title = experience_title;
        model.apply_cnt = apply_cnt;
        
        [self.array addObject:model];
    }
    [resultSet close];
    
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HTTTrippTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuser" forIndexPath:indexPath];
    cell.tripMainModel =  _array[indexPath.row];
    
    //避免一开始拖动的时候图片出现跳动
    CGRect newFrame = cell.picture.frame;
    newFrame.origin.y = -(cell.frame.origin.y - self.tableView.contentOffset.y) / 11 ;
    cell.picture.frame = newFrame;
    
    return cell;
}

//cell滑动的时候改变image的frame;
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSArray *visibleCell = [self.tableView visibleCells];
    
    for (HTTTrippTableViewCell *cell in visibleCell) {
        CGRect newFrame = cell.picture.frame;
        newFrame.origin.y = -(cell.frame.origin.y - self.tableView.contentOffset.y) / 11 ;
        cell.picture.frame = newFrame;
        
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HTTripDeatillViewController *TripDeatilVC = [[HTTripDeatillViewController alloc]init];
    _tripMainModel  = _array[indexPath.row];
    TripDeatilVC.experience_id = _tripMainModel.experience_id;
    TripDeatilVC.navigationController = self.navigationController;
    [self.navigationController pushViewController:TripDeatilVC animated:YES];
    //[self presentViewController:TripDeatilVC animated:YES completion:nil];
}

//拼接URL后面的参数
- (NSString *)page:(NSString *)pagestr
{
    NSString *str = [[TripURL stringByAppendingString:pagestr]stringByAppendingString:@"&type=4"];
    
    return str;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
